﻿using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;

namespace Foundation.Markup
{
    public class ViewModel : MarkupExtension
    {
        public ViewModel() : base(new RelativeSource(RelativeSourceMode.Self))
        {
            Path = new PropertyPath("DataContext");
            Mode = BindingMode.TwoWay;
        }

        public string PropertyKey { get; set; }
        public string DefaultValue { get; set; }
        public IValueConverter FinalConverter { get; set; }
        public IValueConverter FinalConverterParameter { get; set; }
        protected ViewModelBase BindedViewModel { get; set; }

        public override object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var viewModel = value as ViewModelBase;
            BindedViewModel = viewModel ?? BindedViewModel;
            if (BindedViewModel == null) return null;
            var propertyValue = BindedViewModel[PropertyKey, DefaultValue];
            if (FinalConverter != null)
                propertyValue = FinalConverter.Convert(propertyValue, targetType,
                    FinalConverterParameter, culture);
            return propertyValue;
        }

        public override object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (BindedViewModel == null) return null;
            BindedViewModel[PropertyKey] = value;
            if (FinalConverter != null)
                value = FinalConverter.ConvertBack(value, targetType,
                    FinalConverterParameter, culture);
            return value;
        }
    }
}
